package com.bang.concurrency.example.syncContainer;

import com.bang.concurrency.annotations.ThreadSafe;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Auther: Bang
 * @Date: 2019/10/1 20:07
 * @Description:
 */
@Slf4j
@ThreadSafe
public class CollectionsExample3 {

    private static int clientCount = 5000;

    private static int threadCount = 200;

    private static Map<Integer,Integer> map = Collections.synchronizedMap(Maps.newHashMap());


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount);
        final CountDownLatch countDownLatch = new CountDownLatch(clientCount);
        for (int i = 0; i < clientCount; i++) {
           final int count = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        update(count);
                        semaphore.release();
                        countDownLatch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.error("size = {}", map.size());

    }

    private static void update(int count) {
        map.put(count, count);
    }

}
